package backend_store

import (
	"context"
	"encoding/json"
	"xialou_platform/app/errorx"
	"xialou_platform/app/requestx"
	"xialou_platform/app/respx"
	"xialou_platform/app/tools"
	"xialou_platform/services/agent/rpc/agentClient"

	"xialou_platform/services/agent/api/internal/svc"
	"xialou_platform/services/agent/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type StoreReviewLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewStoreReviewLogic(ctx context.Context, svcCtx *svc.ServiceContext) StoreReviewLogic {
	return StoreReviewLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *StoreReviewLogic) StoreReview(req *types.StoreReviewReq) error {
	adminId, err := requestx.FetchUserIdByJwt(l.ctx)
	if err != nil {
		return err
	}
	store, err := l.svcCtx.AgentRpc.StoreById(l.ctx, &agentClient.IdBody{Id: respx.IDParse(req.Id).GetInt64()})
	if err != nil {
		return err
	}

	storeLog, err := l.svcCtx.AgentRpc.StoreLogLatestByStoreId(l.ctx, &agentClient.IdBody{
		Id: respx.IDParse(req.Id).GetInt64(),
	})
	if err != nil {
		return err
	}

	// 审核通过
	if req.Status == 1 {
		// *** 更新到其他平台 ***
		bytes, err := tools.RequestOtherPlatform(
			l.svcCtx.Config.XiuXianApi.StoreUpdate,
			"POST",
			l.svcCtx.Config.Auth.AccessSecret,
			storeLog.Body,
			l.svcCtx.Config.Auth.AccessExpire,
			10000, // admin_users表 下楼系统账户的ID
		)
		if err != nil {
			return err
		}

		var res StoreUpdateRes
		err = json.Unmarshal(bytes, &res)
		if err != nil {
			logx.Infof("调用%v的商户修改接口err：%v", store.Platform, err.Error())
			return errorx.NewMsgReasonCodeError(errorx.DefaultCode, "调用商户修改接口err：%v", err.Error())
		}

		logx.Infof("更新商户: %v", res)
		if res.Code != 200 {
			return errorx.NewCodeReason(res.Code, res.Message)
		}

		// *** 第一次通过，商家用户注册 ***
		if !store.FirstPass {
			regReq := StoreUsersRegisterReq{
				BusinessId: respx.IDFrom(store.StoreId).ToString(),
				Phone:      store.StorePhone,
				NickName:   store.Name,
				IsAdmin:    true,
			}
			regByte, err := json.Marshal(regReq)
			if err != nil {
				return err
			}

			regRes, err := tools.RequestOtherPlatform(
				l.svcCtx.Config.XiuXianApi.StoreUserRegister,
				"POST",
				l.svcCtx.Config.Auth.AccessSecret,
				string(regByte),
				l.svcCtx.Config.Auth.AccessExpire,
				10000, // admin_users表 下楼系统账户的ID
			)
			if err != nil {
				return err
			}
			var regResp StoreUpdateRes
			err = json.Unmarshal(regRes, &regResp)
			if err != nil {
				logx.Infof("调用%v的注册商家用户接口err：%v", store.Platform, err.Error())
				return errorx.NewMsgReasonCodeError(errorx.DefaultCode, "调用注册商家用户接口err：%v", err.Error())
			}

			logx.Infof("注册商家用户: %v", regResp)
			if regResp.Code != 200 {
				return errorx.NewCodeReason(regResp.Code, res.Message)
			}
		}

		// *** 商家上架 ***
		activeReq := UpdateStoreActiveReq{
			StoreId: respx.IDFrom(store.StoreId).ToString(),
			Active:  true,
		}
		activeByte, err := json.Marshal(activeReq)
		if err != nil {
			return err
		}

		activeRes, err := tools.RequestOtherPlatform(
			l.svcCtx.Config.XiuXianApi.StoreActive,
			"POST",
			l.svcCtx.Config.Auth.AccessSecret,
			string(activeByte),
			l.svcCtx.Config.Auth.AccessExpire,
			10000, // admin_users表 下楼系统账户的ID
		)
		if err != nil {
			return err
		}
		var activeResp StoreUpdateRes
		err = json.Unmarshal(activeRes, &activeResp)
		if err != nil {
			logx.Infof("调用%v的商户上架接口err：%v", store.Platform, err.Error())
			return errorx.NewMsgReasonCodeError(errorx.DefaultCode, "调用商户上架接口err：%v", err.Error())
		}

		logx.Infof("更新商户上架: %v", activeResp)
		if activeResp.Code != 200 {
			return errorx.NewCodeReason(activeResp.Code, res.Message)
		}

	}

	if !store.FirstPass && req.Status == 1 {
		store.FirstPass = true
	}
	store.Status = req.Status
	_, err = l.svcCtx.AgentRpc.StoreUpdate(l.ctx, store)
	if err != nil {
		return err
	}

	storeLog.Status = req.Status
	storeLog.Remark = respx.IDFrom(adminId).ToString()
	storeLog.Reviewer = adminId
	_, err = l.svcCtx.AgentRpc.StoreLogUpdate(l.ctx, storeLog)
	if err != nil {
		return err
	}

	return nil
}

type StoreUpdateRes struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}
type StoreUsersRegisterReq struct {
	BusinessId string `json:"businessId,optional"`   // 商家id
	Phone      string `json:"phone"`                 // 用户电话
	NickName   string `json:"nickName"`              // 用户昵称
	IsAdmin    bool   `json:"isAdmin,default=false"` // 管理员
}
type UpdateStoreActiveReq struct {
	StoreId string `json:"store_id"` // 商家ID
	Active  bool   `json:"active"`   // true 上架状态  false 下架状态
}
